﻿using SGA.Model;
using System;
using System.Linq;
using SGA.Classes;
using System.Web.UI.WebControls;

namespace SGA.Associate
{
    public partial class EditAssociates : System.Web.UI.Page
    {
        private const int K_FIRST_COLLECTION = 1;
        private const int K_AMENDMENT_NONE = 1;         //1	<nenhum>
        private const int K_AMENDMENT_CHG_AUTH = 2;     //2	Alteração de autorização bancária
        private const int K_AMENDMENT_CHG_ACC = 3;      //3	Alteração de conta bancária (dentro do mesmo banco)
        private const int K_AMENDMENT_CHG_BNK = 4;      //4	Alteração de Banco
        private const int K_AMENDMENT_CHG_BNK_AUTH = 5; //5	Alteração de Banco e autorização bancária
        private const int K_DONATION_SITUATION_DM = 3;  //3 DM - Donativo Mensal

        private const int K_EXISTING = 0;
        private const int K_NEW = 1;

        private int idSupporter;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string stringId = Request.QueryString["Id"];
                idSupporter = Convert.ToInt32(stringId);
                if (idSupporter > 0)
                {
                    FVAssociates.DataSourceID = "EDSAssociates";
                    EDSAssociates.EnableUpdate = true;
                    EDSAssociates.EnableInsert = false;
                    EDSAssociates.EnableDelete = false;
                    EDSAssociates.AutoGenerateWhereClause = true;
                    Parameter filterNumberSupporters = new Parameter("IdSupporters", System.TypeCode.Int32, idSupporter.ToString());
                    EDSAssociates.WhereParameters.Clear();
                    EDSAssociates.WhereParameters.Add(filterNumberSupporters);

                    FillSuspensionFields();
                }

            }

            ////if (TextBox1.Text.Trim() != string.Empty)
            ////{
            ////IdSupporter = 12;//int.Parse(TextBox1.Text);
            //InvalidIbanNibLbl.Visible = false;
            //NotificationLabel.Text = string.Empty;

            ////if (!IsPostBack)
            ////{
            ////FillPage(IdSupporter);
            ////FillPage();

            ////if (!Master.Page.ClientScript.IsStartupScriptRegistered("alert"))
            ////{
            ////    Master.Page.ClientScript.RegisterStartupScript
            ////        (this.GetType(), "alert", "Confim();", true);
            ////}
            ////}
            ////    TextBox1.Text = string.Empty;
            ////}
        }


        /// <summary>
        /// preenche a TextBox com a sequencia numérica da autorização que deve ser mandada ao Banco
        /// </summary>
        /// <param name="sequence"></param>
        /// <returns></returns>
        public string SequenceNumber(string sequence)
        {
            return Generic.Instance.getResumenSequence(idSupporter, sequence);
        }


        /// <summary>
        /// preenche os campos relativos à suspensão
        /// </summary>
        public void FillSuspensionFields()
        {
            using (MailingEntities bd = new MailingEntities())
            {
                //adquire o maior id para o associado
                int maxId = (from susp in bd.AssociateSuspensions
                             where susp.IdSupporters == idSupporter
                             select susp.Id).DefaultIfEmpty(0).Max();

                if (maxId != 0)
                {
                    //int maxId = qry;
                    AssociateSuspensions qrySusp = (from susp in bd.AssociateSuspensions
                                                    where susp.Id == maxId
                                                    select susp).SingleOrDefault();
                    TextBox txt;
                    txt = FVAssociates.FindControl("ResumingDateTbox") as TextBox;
                    txt.Text = Generic.Instance.formatDateToString(qrySusp.ResumingDate);

                    txt = FVAssociates.FindControl("SuspensionDateTbox") as TextBox;
                    txt.Text = Generic.Instance.formatDateToString(qrySusp.SuspensionDate);

                    DropDownList Ddl;
                    Ddl = FVAssociates.FindControl("SuspensionContatTypeDdl") as DropDownList;
                    Ddl.SelectedValue = qrySusp.IdSuspensionContactTypes.ToString();

                    Ddl = FVAssociates.FindControl("ReasonSuspDdl") as DropDownList;
                    Ddl.SelectedValue = qrySusp.IdReasonForSuspension.ToString();
                }
            }
        }

        /*     --------------------------------------------------------------------- */
        ///// <summary>
        ///// Preenche a página com os dados do Associado, se houver
        ///// </summary>
        ///// <param name="numSupporter"></param>
        ////private void FillPage(int numSupporter)
        //private void FillPage()
        //{
        //    int IdSupporter = int.Parse(NumSupporterTbox.Text);

        //    using (MailingEntities bd = new MailingEntities())
        //    {
        //        //carrega o nome e ID do aderente
        //        SGA.Model.Supporters qrySupp = (from sup in bd.Supporters
        //                                        where sup.Id == IdSupporter
        //                                        select sup).SingleOrDefault();
        //        NameSupporterTbox.Text = qrySupp.Designation;
        //        //NumSupporterTbox.Text = qrySupp.Id.ToString();

        //        //carrega os dados de associado, se houver
        //        var qry = bd.GetAssociatesData(IdSupporter).SingleOrDefault();
        //        if (qry != null)
        //        {
        //            //Trata-se de um Associado já existente
        //            NewAssociateHf.Value = K_EXISTING.ToString();


        //            UserTbox.Text = qry.usr;
        //            LastModificationTbox.Text = Generic.Instance.formatDateToString(qry.LastModification);

        //            //dados bancários
        //            NameOfTbox.Text = qry.NameOf.Trim();
        //            CountryBankTbox.Text = qry.CountryBank;
        //            NumberBankTbox.Text = qry.NumberBank;
        //            NumberAgencyTbox.Text = qry.NumberAgency;
        //            NumberAccountTbox.Text = qry.NumberAccount;
        //            CheckDigitAccountTbox.Text = qry.CheckDigitAccount;

        //            if (qry.ObtainingDate.HasValue)
        //                ObtainDateTbox.Text = Generic.Instance.formatDateToString(qry.ObtainingDate);

        //            BICTbox.Text = qry.BIC;
        //            BankCollectingTypesDdl.SelectedValue = qry.IdBankCollectingTypes.ToString();
        //            ColletionAmendmentDdl.SelectedValue = qry.IdCollectingAmendments.ToString();

        //            //dados da cobrança
        //            DonationSituationDdl.SelectedValue = qry.IdDonationSituations.ToString();
        //            ValueDonationTbox.Text = qry.ValueDonation.ToString();

        //            if (qry.CollectingDate.HasValue)
        //                CollectingDateTbox.Text = Generic.Instance.formatDateToString(qry.CollectingDate);
        //            MaxDonationTbox.Text = qry.MaxDonation.ToString();
        //            AlternativeCollectingValueTbox.Text = qry.AlternativeCollectingValue.ToString();
        //            if (qry.AlternativeCollectingDate.HasValue)
        //                AlternativeCollectingDateTbox.Text = Generic.Instance.formatDateToString(qry.AlternativeCollectingDate);
        //            WantReceiptCbox.Checked = (bool)qry.WantReceipt;

        //            //dados da suspensão
        //            if (qry.SuspensionDate.HasValue)
        //                SuspensionDateTbox.Text = Generic.Instance.formatDateToString(qry.SuspensionDate);
        //            SuspensionContatTypeDdl.SelectedValue = qry.IdSuspensionContactTypes.ToString();
        //            ReasonSuspDdl.SelectedValue = qry.IdReasonForSuspension.ToString();

        //            //observações
        //            ActualAuthorizTbox.Text = Generic.Instance.getResumenSequence(IdSupporter, qry.ResumingSequence.ToString());
        //            if (qry.ResumingDate.HasValue)
        //                ResumingDateTbox.Text = Generic.Instance.formatDateToString(qry.ResumingDate);
        //            SequenceTbox.Text = qry.ResumingSequence.ToString();
        //            ResumingSequenceTbox.Text = string.Empty;
        //            ObservationsTbox.Text = qry.Observations.Trim();
        //        }
        //        else
        //            FillDefaultValues();
        //    }
        //}

        ///// <summary>
        ///// Preenche os dados padrão da página, quando se trata de um novo associado
        ///// </summary>
        //private void FillDefaultValues()
        //{
        //    //Trata-se de um Associado novo
        //    int IdSupporter = int.Parse(NumSupporterTbox.Text);
        //    NewAssociateHf.Value = K_NEW.ToString();

        //    ObtainDateTbox.Text = DateTime.Today.ToString("dd-MM-yyyy");
        //    BankCollectingTypesDdl.SelectedValue = K_FIRST_COLLECTION.ToString();
        //    BankCollectingTypesDdl.Enabled = false;
        //    ColletionAmendmentDdl.SelectedValue = K_AMENDMENT_NONE.ToString();
        //    ColletionAmendmentDdl.Enabled = false;
        //    DonationSituationDdl.SelectedValue = K_DONATION_SITUATION_DM.ToString();
        //    CollectingDateTbox.Text = DateTime.Today.ToString("dd-MM-yyyy");
        //    SequenceTbox.Text = "0";
        //    ActualAuthorizTbox.Text = Generic.Instance.getResumenSequence(IdSupporter, SequenceTbox.Text);
        //    NumberBankTbox.Focus();
        //}

        ///// <summary>
        ///// Valida o IBAN
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //protected void CheckIBANBtn_Click(object sender, EventArgs e)
        //{
        //    //string iban;
        //    //InvalidIbanNibLbl.Visible = false;

        //    //if (CountryBankTbox.Text.Trim() == string.Empty)
        //    //    iban = Iban.K_IBAN_PT;
        //    //else
        //    //    iban = CountryBankTbox.Text.Trim();

        //    //iban += NumberBankTbox.Text.Trim() + NumberAgencyTbox.Text.Trim() + NumberAccountTbox.Text.Trim() + CheckDigitAccountTbox.Text.Trim();
        //    //if (!Iban.Instance.isIBAN(iban))
        //    if (!isValidIBAN())
        //    {
        //        InvalidIbanNibLbl.Text = "IBAN/NIB inválido!";
        //        InvalidIbanNibLbl.BackColor = Color.Red;
        //        InvalidIbanNibLbl.Visible = true;
        //    }
        //    else
        //    {
        //        InvalidIbanNibLbl.Text = "IBAN/NIB Ok!";
        //        InvalidIbanNibLbl.BackColor = Color.Green;
        //        InvalidIbanNibLbl.Visible = true;
        //    }
        //}


        ///// <summary>
        ///// Função auxiliar para validar o IBAN/NIB
        ///// </summary>
        ///// <returns></returns>
        //private bool isValidIBAN()
        //{
        //    string iban;
        //    InvalidIbanNibLbl.Visible = false;

        //    if (CountryBankTbox.Text.Trim() == string.Empty)
        //        iban = Iban.K_IBAN_PT;
        //    else
        //        iban = CountryBankTbox.Text.Trim();

        //    iban += NumberBankTbox.Text.Trim() + NumberAgencyTbox.Text.Trim() + NumberAccountTbox.Text.Trim() + CheckDigitAccountTbox.Text.Trim();
        //    return Iban.Instance.isIBAN(iban);
        //}

        ///// <summary>
        ///// Quando se altera a sequência da autorização é criada uma nova autorização, que é mostrada na TextBox ResumingSequenceTbox
        ///// Essa informação só será guardada se for pressionado o botão "Gravar"
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //protected void SequenceTbox_TextChanged(object sender, EventArgs e)
        //{
        //    int IdSupporter = int.Parse(NumSupporterTbox.Text);
        //    string sequence = SequenceTbox.Text.Trim();

        //    if (sequence != string.Empty)
        //        ResumingSequenceTbox.Text = Generic.Instance.getResumenSequence(IdSupporter, SequenceTbox.Text);
        //}

        ///// <summary>
        ///// A alteração do número de Banco provoca a mudança do status de cobrança para "First" e 
        ///// uma alteração da cobrança para "alteração de Banco"
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //protected void NumberBankTbox_TextChanged(object sender, EventArgs e)
        //{
        //    BankCollectingTypesDdl.SelectedValue = K_FIRST_COLLECTION.ToString();
        //    ColletionAmendmentDdl.SelectedValue = K_AMENDMENT_CHG_BNK.ToString();
        //}

        ///// <summary>
        ///// A alteração do NIB apenas provoca uma alteração da cobrança para "Alteração de conta bancária (dentro do mesmo banco)"
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //protected void NumberAgencyTbox_TextChanged(object sender, EventArgs e)
        //{
        //    if (ColletionAmendmentDdl.SelectedValue != K_AMENDMENT_CHG_BNK.ToString() &&
        //        ColletionAmendmentDdl.SelectedValue != K_AMENDMENT_CHG_BNK_AUTH.ToString())

        //        ColletionAmendmentDdl.SelectedValue = K_AMENDMENT_CHG_ACC.ToString();
        //}

        ///// <summary>
        ///// A operação de Reatamento limpa os dados da suspensão, incrementa a sequência de autorização em uma unidade,
        ///// atribui a data do dia à textBox data de reatamento, mostra o número da nova autorização, muda o status da cobrança 
        ///// para "First - primeira cobrança", bloqueia a combo de alterações de cobrança e muda a DropDownList 
        ///// "Tipo de contribuição" para "DM"
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //protected void ReatamentoBtn_Click(object sender, EventArgs e)
        //{
        //    int IdSupporter = int.Parse(NumSupporterTbox.Text);

        //    BankCollectingTypesDdl.SelectedValue = K_FIRST_COLLECTION.ToString();
        //    ColletionAmendmentDdl.SelectedValue = K_AMENDMENT_NONE.ToString();
        //    ColletionAmendmentDdl.Enabled = false;

        //    DonationSituationDdl.SelectedValue = K_DONATION_SITUATION_DM.ToString();
        //    SuspensionDateTbox.Text = string.Empty;
        //    SuspensionContatTypeDdl.SelectedValue = string.Empty;
        //    ReasonSuspDdl.SelectedValue = string.Empty;

        //    ResumingDateTbox.Text = DateTime.Today.ToString();
        //    int seq = int.Parse(SequenceTbox.Text);
        //    seq++;
        //    SequenceTbox.Text = seq.ToString();
        //    ResumingSequenceTbox.Text = Generic.Instance.getResumenSequence(IdSupporter, seq.ToString());
        //    NumberBankTbox.Focus();
        //}

        ///// <summary>
        ///// Grava as alterações feitas no formulário
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //protected void SaveBtn_Click(object sender, EventArgs e)
        //{
        //    NotificationLabel.Text = string.Empty;
        //    if (canSave())
        //    {
        //        string login = Page.User.Identity.Name;
        //        int idUser;

        //        using (var bd = new MailingEntities())
        //        {
        //            var usr = (from user in bd.SystemUsers
        //                       where user.Username == login
        //                       select user).SingleOrDefault();
        //            idUser = usr.Id;
        //        }

        //        if (int.Parse(NewAssociateHf.Value) == K_NEW)
        //        {
        //            SaveAssociate(idUser);
        //        }
        //        else
        //        {
        //            UpdateAssociate(idUser);
        //        }
        //    }
        //}

        ///// <summary>
        ///// Grava os dados do novo Associado
        ///// </summary>
        //private void SaveAssociate(int idUser)
        //{
        //    try
        //    {
        //        int IdSupporter = int.Parse(NumSupporterTbox.Text);

        //        Associates newAssociate = new Associates();
        //        AssociateSuspensions newSuspension = new AssociateSuspensions();

        //        newAssociate.IdSupporters = IdSupporter;
        //        newAssociate.NameOf = NameOfTbox.Text.Trim();
        //        newAssociate.CountryBank = CountryBankTbox.Text.Trim();
        //        newAssociate.NumberBank = NumberBankTbox.Text.Trim();
        //        newAssociate.NumberAgency = NumberAgencyTbox.Text.Trim();
        //        newAssociate.NumberAccount = NumberAccountTbox.Text.Trim();
        //        newAssociate.CheckDigitAccount = CheckDigitAccountTbox.Text.Trim();
        //        newAssociate.ObtainingDate = Convert.ToDateTime(ObtainDateTbox.Text.Trim());
        //        newAssociate.BIC = BICTbox.Text.Trim();
        //        newAssociate.IdBankCollectingTypes = int.Parse(BankCollectingTypesDdl.SelectedValue);
        //        newAssociate.IdCollectingAmendments = int.Parse(ColletionAmendmentDdl.SelectedValue);
        //        newAssociate.IdDonationSituations = int.Parse(DonationSituationDdl.SelectedValue);
        //        newAssociate.ValueDonation = decimal.Parse(ValueDonationTbox.Text.Trim());
        //        newAssociate.CollectingDate = Convert.ToDateTime(CollectingDateTbox.Text.Trim());

        //        if (MaxDonationTbox.Text.Trim() != string.Empty)
        //            newAssociate.MaxDonation = decimal.Parse(MaxDonationTbox.Text.Trim());
        //        else
        //            newAssociate.MaxDonation = null;

        //        if (AlternativeCollectingValueTbox.Text.Trim() != string.Empty)
        //            newAssociate.AlternativeCollectingValue = decimal.Parse(AlternativeCollectingValueTbox.Text.Trim());
        //        else
        //            newAssociate.AlternativeCollectingValue = null;

        //        if (AlternativeCollectingDateTbox.Text.Trim() != string.Empty)
        //            newAssociate.AlternativeCollectingDate = Convert.ToDateTime(AlternativeCollectingDateTbox.Text.Trim());
        //        else
        //            newAssociate.AlternativeCollectingDate = null;

        //        newAssociate.WantReceipt = WantReceiptCbox.Checked;

        //        if (SuspensionDateTbox.Text.Trim() != string.Empty)
        //            newAssociate.SuspensionDate = Convert.ToDateTime(SuspensionDateTbox.Text.Trim());
        //        else
        //            newAssociate.SuspensionDate = null;

        //        if (ReasonSuspDdl.SelectedValue.ToString().Trim() != string.Empty)
        //            newAssociate.IdReasonForSuspension = int.Parse(ReasonSuspDdl.SelectedValue);
        //        else
        //            newAssociate.IdReasonForSuspension = null;

        //        if (SuspensionContatTypeDdl.SelectedValue.ToString().Trim() != string.Empty)
        //            newAssociate.IdSuspensionContactTypes = int.Parse(SuspensionContatTypeDdl.SelectedValue);
        //        else
        //            newAssociate.IdSuspensionContactTypes = null;

        //        //if (ResumingDateTbox.Text.Trim() != string.Empty)
        //        //    newAssociate.ResumingDate = Convert.ToDateTime(ResumingDateTbox.Text.Trim());
        //        //else
        //        //    newAssociate.ResumingDate = null;

        //        newAssociate.ResumingSequence = int.Parse(SequenceTbox.Text.Trim());
        //        newAssociate.Observations = ObservationsTbox.Text.Trim();
        //        newAssociate.LastModification = DateTime.Today;
        //        newAssociate.IdSystemUsers = idUser;

        //        using (MailingEntities bd = new MailingEntities())
        //        {
        //            var qry = from associate in bd.Associates
        //                      where associate.IdSupporters == IdSupporter
        //                      select associate;

        //            if (qry.Count() > 0)
        //            {
        //                throw new Exception("Já existe um Associado com esse número: " + IdSupporter.ToString() + "!");
        //            }

        //            bd.Associates.Add(newAssociate);
        //            bd.SaveChanges();

        //            try
        //            {
        //                if (SuspensionDateTbox.Text.Trim() != string.Empty)
        //                {
        //                    newSuspension.IdSupporters = IdSupporter;
        //                    newSuspension.SuspensionDate = Convert.ToDateTime(SuspensionDateTbox.Text.Trim());

        //                    if (ReasonSuspDdl.SelectedItem.Text.Trim() != string.Empty)
        //                        newSuspension.IdReasonForSuspension = int.Parse(ReasonSuspDdl.SelectedValue);

        //                    if (SuspensionContatTypeDdl.SelectedItem.Text.Trim() != string.Empty)
        //                        newSuspension.IdSuspensionContactTypes = int.Parse(SuspensionContatTypeDdl.SelectedValue);

        //                    if (ResumingDateTbox.Text.Trim() != string.Empty)
        //                        newSuspension.ResumingDate = Convert.ToDateTime(ResumingDateTbox.Text.Trim());

        //                    bd.AssociateSuspensions.Add(newSuspension);
        //                    bd.SaveChanges();
        //                }
        //            }
        //            catch (SqlException e)
        //            {
        //                NotificationLabel.Text = "(" + e.Number.ToString() + ") ";
        //                NotificationLabel.Text += e.Message.ToString();
        //            }
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        NotificationLabel.Text = String.Format("{0}", e.Message);
        //        //NotificationLabel.Text = e.Message.ToString();
        //    }
        //}


        //private void UpdateAssociate(int idUser)
        //{
        //    try
        //    {
        //        int IdSupporter = int.Parse(NumSupporterTbox.Text);
        //        using (var bd = new MailingEntities())
        //        {
        //            Associates updAssociate = (from assoc in bd.Associates
        //                                       where assoc.IdSupporters == IdSupporter
        //                                       select assoc).SingleOrDefault();

        //            updAssociate.NameOf = NameOfTbox.Text.Trim();
        //            updAssociate.CountryBank = CountryBankTbox.Text.Trim();
        //            updAssociate.NumberBank = NumberBankTbox.Text.Trim();
        //            updAssociate.NumberAgency = NumberAgencyTbox.Text.Trim();
        //            updAssociate.NumberAccount = NumberAccountTbox.Text.Trim();
        //            updAssociate.CheckDigitAccount = CheckDigitAccountTbox.Text.Trim();
        //            updAssociate.BIC = BICTbox.Text.Trim();
        //            updAssociate.IdBankCollectingTypes = int.Parse(BankCollectingTypesDdl.SelectedValue);
        //            updAssociate.IdCollectingAmendments = int.Parse(ColletionAmendmentDdl.SelectedValue);
        //            updAssociate.IdDonationSituations = int.Parse(DonationSituationDdl.SelectedValue);
        //            updAssociate.ValueDonation = decimal.Parse(ValueDonationTbox.Text.Trim());
        //            updAssociate.CollectingDate = Convert.ToDateTime(CollectingDateTbox.Text.Trim());

        //            if (MaxDonationTbox.Text.Trim() != string.Empty)
        //                updAssociate.MaxDonation = decimal.Parse(MaxDonationTbox.Text.Trim());
        //            else
        //                updAssociate.MaxDonation = null;

        //            if (AlternativeCollectingValueTbox.Text.Trim() != string.Empty)
        //                updAssociate.AlternativeCollectingValue = decimal.Parse(AlternativeCollectingValueTbox.Text.Trim());
        //            else
        //                updAssociate.AlternativeCollectingValue = null;

        //            if (AlternativeCollectingDateTbox.Text.Trim() != string.Empty)
        //                updAssociate.AlternativeCollectingDate = Convert.ToDateTime(AlternativeCollectingDateTbox.Text.Trim());
        //            else
        //                updAssociate.AlternativeCollectingDate = null;

        //            updAssociate.WantReceipt = WantReceiptCbox.Checked;

        //            if (SuspensionDateTbox.Text.Trim() != string.Empty)
        //                updAssociate.SuspensionDate = Convert.ToDateTime(SuspensionDateTbox.Text.Trim());
        //            else
        //                updAssociate.SuspensionDate = null;

        //            if (ReasonSuspDdl.SelectedValue.ToString().Trim() != string.Empty)
        //                updAssociate.IdReasonForSuspension = int.Parse(ReasonSuspDdl.SelectedValue);
        //            else
        //                updAssociate.IdReasonForSuspension = null;

        //            if (SuspensionContatTypeDdl.SelectedValue.ToString().Trim() != string.Empty)
        //                updAssociate.IdSuspensionContactTypes = int.Parse(SuspensionContatTypeDdl.SelectedValue);
        //            else
        //                updAssociate.IdSuspensionContactTypes = null;

        //            //if (ResumingDateTbox.Text.Trim() != string.Empty)
        //            //    updAssociate.ResumingDate = Convert.ToDateTime(ResumingDateTbox.Text.Trim());
        //            //else
        //            //    updAssociate.ResumingDate = null;

        //            updAssociate.ResumingSequence = int.Parse(SequenceTbox.Text.Trim());
        //            updAssociate.Observations = ObservationsTbox.Text.Trim();
        //            updAssociate.LastModification = DateTime.Today;
        //            updAssociate.IdSystemUsers = idUser;

        //            bd.SaveChanges();

        //            try
        //            {
        //                AssociateSuspensions newSuspension = new AssociateSuspensions();

        //                newSuspension.IdSupporters = IdSupporter;

        //                //se houver cancelamento, adiciona os dados
        //                if (SuspensionDateTbox.Text.Trim() != string.Empty)
        //                {
        //                    newSuspension.SuspensionDate = Convert.ToDateTime(SuspensionDateTbox.Text.Trim());
        //                    newSuspension.IdReasonForSuspension = updAssociate.IdReasonForSuspension;
        //                    newSuspension.IdSuspensionContactTypes = updAssociate.IdSuspensionContactTypes;
        //                }
        //                else
        //                {
        //                    newSuspension.SuspensionDate = null;
        //                    newSuspension.IdReasonForSuspension = null;
        //                    newSuspension.IdSuspensionContactTypes = null;
        //                }

        //                if (ResumingDateTbox.Text.Trim() != string.Empty)
        //                    newSuspension.ResumingDate = Convert.ToDateTime(ResumingDateTbox.Text.Trim());
        //                else
        //                    newSuspension.ResumingDate = null;

        //                bd.AssociateSuspensions.Add(newSuspension);
        //                bd.SaveChanges();
        //            }
        //            catch (DbUpdateException ex)
        //            {
        //                //não faz nada. 


        //                NotificationLabel.Text = ex.Message.ToString();

        //                ////if (null == ex.InnerException || ex.InnerException.InnerException == null) throw;

        //                //var innerException = ex.InnerException.InnerException as System.Data.SqlClient.SqlException;
        //                //if (innerException != null &&
        //                //       (
        //                //           innerException.Number == 2627 ||
        //                //           innerException.Number == 2601)
        //                //       )
        //                //{
        //                //    throw; //new AlreadyInsertedException();
        //                //}
        //                //else
        //                //{
        //                //    throw;
        //                //}
        //            }
        //            catch (Exception e)
        //            {
        //                NotificationLabel.Text = e.Message.ToString();
        //            }
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        NotificationLabel.Text = e.Message.ToString();
        //    }

        //}

        ///// <summary>
        ///// valida os campos antes de fazer a actualização
        ///// </summary>
        ///// <returns></returns>
        //private bool canSave()
        //{
        //    string newValue;

        //    //validação dos dados bancários
        //    newValue = NumberBankTbox.Text ?? string.Empty;
        //    if (newValue == string.Empty || !Generic.Instance.isNumeric(newValue))
        //    {
        //        NotificationLabel.Text = "O campo 'Banco' deve ser Numérico ou estar preenchido!";
        //        return false;
        //    }

        //    newValue = NumberAgencyTbox.Text ?? string.Empty;
        //    if (newValue == string.Empty || !Generic.Instance.isNumeric(newValue))
        //    {
        //        NotificationLabel.Text = "O campo 'Agência' deve ser Numérico ou estar preenchido!";
        //        return false;
        //    }

        //    newValue = NumberAccountTbox.Text ?? string.Empty;
        //    if (newValue == string.Empty || !Generic.Instance.isNumeric(newValue))
        //    {
        //        NotificationLabel.Text = "O campo 'Nº conta' deve ser Numérico ou estar preenchido!";
        //        return false;
        //    }

        //    newValue = CheckDigitAccountTbox.Text ?? string.Empty;
        //    if (newValue == string.Empty || !Generic.Instance.isNumeric(newValue))
        //    {
        //        NotificationLabel.Text = "O campo 'Dígito controlo' deve ser Numérico ou estar preenchido!";
        //        return false;
        //    }

        //    //dados da cobrança
        //    newValue = DonationSituationDdl.Text ?? string.Empty;
        //    if (newValue == string.Empty)
        //    {
        //        NotificationLabel.Text = "O campo 'Tipo contribuição' deve ter um valor!";
        //        return false;
        //    }

        //    newValue = ValueDonationTbox.Text ?? string.Empty;
        //    if (newValue == string.Empty)
        //    {
        //        NotificationLabel.Text = "O campo 'Valor da contribuição' deve estar preenchido!";
        //        return false;
        //    }

        //    newValue = CollectingDateTbox.Text ?? string.Empty;
        //    if (newValue == string.Empty)
        //    {
        //        NotificationLabel.Text = "O campo 'Data da cobrança' deve estar preenchido!";
        //        return false;
        //    }

        //    if (!isValidIBAN())
        //    {
        //        NotificationLabel.Text = "O IBAN/NIB não é válido!";
        //        return false;
        //    }

        //    return true;

        //    //if (qry.CollectingDate.HasValue)
        //    //    CollectingDateTbox.Text = Generic.Instance.formatDateToString(qry.CollectingDate);
        //    //MaxDonationTbox.Text = qry.MaxDonation.ToString();
        //    //AlternativeCollectingValueTbox.Text = qry.AlternativeCollectingValue.ToString();
        //    //if (qry.AlternativeCollectingDate.HasValue)
        //    //    AlternativeCollectingDateTbox.Text = Generic.Instance.formatDateToString(qry.AlternativeCollectingDate);
        //    //WantReceiptCbox.Checked = (bool)qry.WantReceipt;

        //    ////dados da suspensão
        //    //if (qry.SuspensionDate.HasValue)
        //    //    SuspensionDateTbox.Text = Generic.Instance.formatDateToString(qry.SuspensionDate);
        //    //SuspensionContatTypeDdl.SelectedValue = qry.IdSuspensionContactTypes.ToString();
        //    //ReasonSuspDdl.SelectedValue = qry.IdReasonForSuspension.ToString();

        //    ////observações
        //    //ActualAuthorizTbox.Text = Generic.Instance.getResumenSequence(numSupporter, qry.ResumingSequence.ToString());
        //    //if (qry.ResumingDate.HasValue)
        //    //    ResumingDateTbox.Text = Generic.Instance.formatDateToString(qry.ResumingDate);
        //    //SequenceTbox.Text = qry.ResumingSequence.ToString();
        //    //ResumingSequenceTbox.Text = string.Empty;
        //    //ObservationsTbox.Text = qry.Observations.Trim();

        //}

        //protected void Button1_Click(object sender, EventArgs e)
        //{
        //    if (TextBox1.Text.Trim() != string.Empty)
        //    {
        //        //IdSupporter = int.Parse(TextBox1.Text);
        //        NumSupporterTbox.Text = TextBox1.Text;
        //        FillPage();
        //        TextBox1.Text = string.Empty;
        //    }
        //}



    }
}